import { List, Modal, Spin, Button } from 'antd'
import { pageItemLog } from '@/services/project/itemLog'
import React, { useState, useEffect } from 'react';
import UserBrief from '@/components/UserBrief';
import styles from './style.less'
import ArrayUtils from '@/utils/ArrayUtils'
import { RightOutlined, ReadOutlined } from '@ant-design/icons'
import RichText from '@/components/RichText'
import { Link } from 'umi';
import ProjectItemLink from '@/pages/projects/components/ProjectItemLink'


const DataItem = ({ content, fieldName, renderField, renderFieldName, renderModalWidth }) => {

    const [changeDetailModalVisible, setChangeDetailModalVisible] = useState(false)


    return (<div className={styles.dataItemInfo}>
        <div onClick={() => {
            setChangeDetailModalVisible(true)
        }}>
            {renderField(content, fieldName, true, false)}
        </div>
        <Modal
            visible={changeDetailModalVisible}
            closable={true}
            footer={null}
            keyboard={true}
            width={renderModalWidth(fieldName)}
            onCancel={() => {
                setChangeDetailModalVisible(false)
            }}
        >
            <div className={styles.dataItemModalItem}>
                <div className={styles.dataItemModalItemFieldName}>{renderFieldName(fieldName) + ":"}</div>
                <div className={styles.dataItemModalItemOldValue}>
                    {renderField(content, fieldName, false, true)}
                </div>
                <RightOutlined></RightOutlined>
                <div className={styles.dataItemModalItemNewValue}>
                    {renderField(content, fieldName, true, true)}
                </div>
            </div>
        </Modal>
    </div>)

}

const DataMsgItem = ({ content, renderField, renderFieldName, renderModalWidth }) => {

    const [changeDetailModalVisible, setChangeDetailModalVisible] = useState(false)

    const keys = Object.keys(content?.oldData) || []
    ArrayUtils.remove(keys, "id")
    ArrayUtils.remove(keys, "payload")
    return (<div >
        {keys.length > 0 ?
            (<div className={styles.dataItemInfo} onClick={() => {
                setChangeDetailModalVisible(true)
            }}>
                {content?.msg} { <ReadOutlined />}
            </div>) : content?.msg
        }
        {content?.remark?.text && content?.remark?.text !== "<p></p>" &&
            <div className={styles.remark}>

                <RichText
                    ellipsis
                    value={content?.remark?.text}>
                </RichText>
            </div>
        }
        <Modal
            visible={changeDetailModalVisible}
            closable={true}
            footer={null}
            keyboard={true}
            width={renderModalWidth()}
            onCancel={() => {
                setChangeDetailModalVisible(false)
            }}
        >
            {keys && keys.map((keyName) => {
                return (<div key={keyName}>
                    <div className={styles.dataItemModalItem}>
                        <div className={styles.dataItemModalItemFieldName}>{renderFieldName(keyName) + ":"}</div>
                        <div className={styles.dataItemModalItemOldValue}>
                            {renderField(content, keyName, false, true)}
                        </div>
                        <RightOutlined></RightOutlined>
                        <div className={styles.dataItemModalItemNewValue}>
                            {renderField(content, keyName, true, true)}
                        </div>
                    </div>
                </div>)
            })}
        </Modal>
    </div>)

}


const ProjectItemLog = (props) => {

    const {
        projectId,
        itemId,
        itemType,
        renderFieldName,
        renderField,
        renderModalWidth,
        update
    } = props;

    const [logList, setLogList] = useState([])
    const [logPageData, setLogPageData] = useState()
    const [nextLogPageLoading, setNextLogPageLoading] = useState(false);

    useEffect(() => {
        if (itemId) {
            pageItemLog(projectId, itemType, itemId)
                .then((result) => {
                    setLogList([...result?.data?.list])
                    setLogPageData(result?.data)
                })
        }
    }, [itemId, update])


    const renderLocalFieldName = (fieldName) => {
        let name;
        if (renderFieldName) {
            name = renderFieldName(fieldName)
        }
        if (name) {
            return name;
        }
        if (fieldName === "name") {
            return "名称"
        }
        if (fieldName === "status") {
            return "状态"
        }
        if (fieldName === "userId") {
            return "负责人"
        }
        if (fieldName === "description") {
            return "描述"
        }
        if (fieldName === "content") {
            return "内容"
        }
        if (fieldName === "projectProdItemId") {
            return "迭代"
        }
    }

    const renderLocalModalWidth = (fieldName) => {
        let modalWidth;
        if (renderModalWidth) {
            modalWidth = renderModalWidth(fieldName);
        }
        if (modalWidth) {
            return modalWidth;
        }
        if (fieldName === "content") {
            return "80%"
        }
        if (fieldName === "description") {
            return "80%"
        }
    }

    const renderLocalField = (content, fieldName, isNew, isDetail) => {
        let field;
        let data = isNew ? content.newData : content.oldData

        if (renderField) {
            if (Array.isArray(fieldName)) {
                field = renderField(data, fieldName, isDetail)
            } else {
                field = renderField(data && data[fieldName], fieldName, isDetail, data)
            }
        }
        if (field === "read") {
            return <ReadOutlined />
        }
        if (field) {
            return field;
        }
        if (fieldName === "name") {
            return data[fieldName];
        }
        if (fieldName === "description") {
            return isDetail ? <p>{data[fieldName]}</p> : <ReadOutlined />;
        }
        if (fieldName === "content") {
            return isDetail ? <RichText
                ellipsis
                value={data[fieldName].text}>
            </RichText> : <ReadOutlined />;
        }
        if (fieldName === "userId" || fieldName.indexOf("UserId") >= 0) {
            let userPayLoad = data?.payload && data.payload[fieldName];
            return isDetail ? <UserBrief showAvatar={false} user={{
                id: data[fieldName],
                nickName: userPayLoad
            }} /> : (data.payload ? userPayLoad : '未知');
        }
        if (fieldName === "projectProdItemId") {
            if (!isDetail) {
                return itemPayLoad;
            }
            let itemPayLoad = data?.payload && data.payload[fieldName];
            return <ProjectItemLink {...{
                name: itemPayLoad,
                id: data[fieldName],
                projectId: projectId,
                type: "PROD"
            }} />
        }
        if (fieldName === "projectDevItemId") {
            let itemPayLoad = data?.payload && data.payload[fieldName];
            if (!isDetail) {
                return itemPayLoad;
            }
            return <ProjectItemLink {...{
                name: itemPayLoad,
                id: data[fieldName],
                projectId: projectId,
                type: "DEV"
            }} />
        }
        if (fieldName === "projectQaItemId") {
            let itemPayLoad = data?.payload && data.payload[fieldName];
            if (!isDetail) {
                return itemPayLoad
            }
            return <ProjectItemLink {...{
                name: itemPayLoad,
                id: data[fieldName],
                projectId: projectId,
                type: "QA"
            }} />
        }
    }

    const logItemRender = (item) => {
        let operType = item.content?.operType;
        if (operType === 0) {
            // 字端更新的
            let fieldNames = Object.keys(item.content?.newData)
            ArrayUtils.remove(fieldNames, "id")
            ArrayUtils.remove(fieldNames, "payload")
            if (fieldNames.length === 0 || !item.content?.newData) {
                return "没有修改任何值"
            }
            if (fieldNames.length === 1) {
                let updateName = renderLocalFieldName(fieldNames[0])
                return <div className={styles.logItemLine}>
                    编辑了
                    {/* {item.content?.newData[fieldNames[0]]} */}
                    <div className={styles.fieldName}><span>&nbsp;</span>{updateName}</div>
                    <span>&nbsp;为&nbsp;</span>
                    <DataItem content={item.content} renderModalWidth={renderLocalModalWidth} renderFieldName={renderLocalFieldName} renderField={renderLocalField} fieldName={fieldNames[0]} />
                </div>
            }
            let updateName = renderLocalFieldName(fieldNames)
            return <div className={styles.logItemLine}>
                编辑了
                    {/* {item.content?.newData[fieldNames[0]]} */}
                <div className={styles.fieldName}><span>&nbsp;</span>{updateName}</div>
                <span>&nbsp;为&nbsp;</span>
                <DataItem content={item.content} renderModalWidth={renderLocalModalWidth} renderFieldName={renderLocalFieldName} renderField={renderLocalField} fieldName={fieldNames} />
            </div>
        }

        if (operType === 1) {
            //  直接展示文字
            return item.content?.msg
        }

        if (operType === 3) {
            //  直接展示文字
            return <DataMsgItem content={item.content} renderModalWidth={renderLocalModalWidth} renderFieldName={renderLocalFieldName} renderField={renderLocalField} />

        }

        if (operType === 2) {
            //  根据内容拼接
            let items = item.content?.items || []
            return items.map((msgData, index) => {
                if (msgData.hasPayload) {
                    if (msgData.payloadType === "DEMAND") {
                        return <Link key={msgData.payload?.id} to={{
                            pathname: `/projects/${projectId}/demand/${msgData.payload?.id}`,
                        }}>{msgData.msg}</Link>
                    }
                } else {
                    return <span key={`${index}`}>
                        {msgData.msg}
                    </span>
                }
            })
        }
    }
    const onLoadMore = () => {
        setNextLogPageLoading(true)
        pageItemLog(projectId, itemType, itemId, {
            pageNum: logPageData.pageNum + 1
        }).then((result) => {
            setLogList([...logList, ...result?.data?.list])
            setLogPageData(result?.data)
            setNextLogPageLoading(false)
        })
    }

    const loadMore =
        (!logPageData) || logPageData.pageNum >= logPageData.totalPage ?
            '' :
            (<div
                style={{
                    textAlign: 'center',
                    marginTop: 8,
                    height: 24,
                    lineHeight: '24px',
                }}
            >
                {nextLogPageLoading ? <Spin></Spin> :
                    <Button onClick={onLoadMore}>加载更多评论</Button>
                }

            </div>)

    return <div>
        <List
            className={styles.logList}
            dataSource={logList}
            loadMore={loadMore}
            renderItem={item => (
                <List.Item key={item.id}>
                    <div>
                        <div className={styles.logItem}>
                            <UserBrief showAvatar={false} user={item.content.user} /> : {logItemRender(item)}
                        </div>
                        <div className={styles.logCreateTime}>
                            {item.createTime}
                        </div>
                    </div>
                </List.Item>
            )}
        >
        </List>
    </div>

}


export default ProjectItemLog;